import React, { Component } from 'react';
import {
    CaretDownOutlined,
    WifiOutlined
} from '@ant-design/icons';
import { Input, Button, message } from 'antd'
import { robat } from '../../utils/Ajax'
interface IProps {
    chageFlag: ()=>void
}

interface IState {
    val:string,

}


class index extends Component<IProps, IState> {

      constructor(props:IProps) {
          super(props);
          this.state = {
            val:''
          }
      }
    /**
     * 点击按钮发送
     */
    handleSend = ()=> {
    // 1. 获取state的值,判断是否有值,如果没有值就直接结束
       const cusmar = this.state.val.trim()
        if(cusmar === '') return;
        let page = document.getElementById('chatMain')
    // 2.如果有值,就进行一定的加工处理
        let sentence = ` <div class='sentence'>${this.state.val}</div>`;
        page!.insertAdjacentHTML('beforeend',sentence);
        // 3. 发送页面成功后,将信息发送给思知机器人
        this.sendRobat(cusmar)
    }
    /**
     * input的受控组件
     */
    handleChange = (event: any)=> {
        let val = event.target.value;
        this.setState({val})
    }
    /**
     * 统一发送机器人的接口处理方法
     */
    sendRobat = (params:any) =>{        
        robat(params).then((res:any)=> {
            // 1. 发送成功
            if(res.message === 'success') {
                const result = res.data.info.text;
                let page = document.getElementById('chatMain')
                // 2.如果有值,就进行一定的加工处理
                    let sentence = `<div class='sentence1'>${result}</div>`;
                    page!.insertAdjacentHTML('beforeend',sentence);
            }else{
                message.warn('客服休息了');
            }
            
        })
    }

    handlechangeFlag = ()=> {
        this.props.chageFlag();
    }
    

    render() {
        return (
           <div className= 'chat'>
            <div className='chat_header'>
                在线客服
                <div className='chat_header_down' onClick={this.handlechangeFlag}>
                    <CaretDownOutlined />
                </div>
            </div>
            <div className="chat_main" id="chatMain">
             
            </div>
            <div className="chat_search">
                <div className='chat_search_icon'>
                <WifiOutlined />
                </div>
                <div className="chat_search_main">
                    <Input placeholder="您有什么疑问吗" value={this.state.val} onChange={this.handleChange}/>
                </div>
                <div className="chat_search_send">
                    <Button type="link" onClick={this.handleSend}>发送</Button>
                </div>
            </div>
        </div>           
        );
    }
}

export default index;
